package com.alan.android.sqlite;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import androidx.annotation.Nullable;

import com.alan.android.sqlite.patcher.AndroidPatcher;
import com.alan.android.sqlite.patcher.IAndroidPatcher;
import com.alan.android.sqlite.table.Table;
import com.alan.android.sqlite.table.TableFactory;

import java.util.List;

public class DatabaseHelper extends SQLiteOpenHelper {

    private List<Class> tableList;

    private final String TAG = "DatabaseHelper";

    public DatabaseHelper(@Nullable Context context, String name, int version, List<Class> tableList) {
        super(context, name, null, version);
        this.tableList = tableList;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        Log.d("DatabaseHelper", "onCreate 表：" + "开始创建");
        for (Class clazz : tableList) {
            try {
                Table table = TableFactory.getTable(clazz);
                String sql = table.getCreateSqlStr();
                Log.d(TAG, "create table:" + table.getTableName() + "  sql:" + sql);
                sqLiteDatabase.execSQL(sql);
            } catch (Exception e) {
                Log.e(TAG, Log.getStackTraceString(e));
            }
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
        Log.d("DatabaseHelper", "onUpgrade oldVersion:"+oldVersion+" newVersion:"+newVersion);
        for (Class clazz : tableList) {
            try {
                AndroidPatcher annotation = (AndroidPatcher) clazz.getAnnotation(AndroidPatcher.class);
                Class<? extends IAndroidPatcher>[] name = annotation.name();
                if (null != name && name.length > 0) {
                    for (Class<? extends IAndroidPatcher> patcher : name) {
                        try {
                            Log.d(TAG,"onUpgrade step find");
                            IAndroidPatcher inst = patcher.newInstance();
                            int max = inst.getSupportMaxVersion();
                            if (oldVersion < max) {
                                Log.d(TAG,"onUpgrade step execute");
                                inst.execute(sqLiteDatabase);
                            }
                        } catch (Exception e) {
                            Log.e(TAG,Log.getStackTraceString(e));
                        }
                    }
                }
            } catch (Exception e) {
                Log.e(TAG,Log.getStackTraceString(e));
            }
        }
    }

}
